package conversion.controller;

import conversion.bean.Plugin;
import conversion.plugin.ConvertPlugin;
import conversion.plugin.PluginManager;
import conversion.service.PluginService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class PluginController {

    @Resource
    PluginService pluginService;

    @Resource
    PluginManager pluginManager;

    @GetMapping("/convertPlugin")
    public void convertPlugin(){
        Map<String, Object> map = pluginManager.loadPlugins();
        System.out.println(map.toString());
        ConvertPlugin convertPlugin = (ConvertPlugin)map.get("XMLtoCSV");
        System.out.println(convertPlugin.convert("12"));

    }

    @PostMapping("/uploadPlugin")
    public String handleFileUpload(@RequestPart("file") MultipartFile file) {
        // 检查是否有文件被上传
        if (file.isEmpty()) {
            return "No file uploaded.";
        }

        try {
            // 获取文件名
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
//            if (!fileName.endsWith(".jar")) {
//                return "Wrong file format.";
//            }
            // 设置保存路径
            String uploadDir = "D:\\Software\\JAVA\\Project\\code-conversion\\src\\main\\java\\conversion\\pluginFiles\\";
            String filePath = uploadDir + fileName;


            // 创建保存文件的目录（如果不存在）
            File directory = new File(uploadDir);
            if (!directory.exists()) {
                directory.mkdirs();
            }
//            System.out.println(filePath);
            // 保存文件
            file.transferTo(new File(filePath));

            pluginService.insertPlugin(new Plugin(null,fileName,filePath,false));

            return "File uploaded successfully.";
        } catch (IOException e) {
            return "Failed to upload file.";
        }
    }


    @GetMapping("/getAllPlugins")
    public Map<String, Object> getAllPlugins(@RequestParam("page") int page,
                                           @RequestParam("pageSize") int pageSize,
                                           @RequestParam("search") String searchInputValue) {

//         创建用于存储结果的 Map
        Map<String, Object> resultMap = new HashMap<>();

        // 计算分页的起始索引
        int startIndex = (page - 1) * pageSize;

        List<conversion.bean.Plugin> allPlugins;

        if (searchInputValue == null || searchInputValue.equals("")) {
            // 调用 fileService 的方法获取所有文件
            allPlugins = pluginService.getAllPlugins();
        }else {

            allPlugins = pluginService.getPluginByValue(searchInputValue);
        }

        // 根据分页参数截取当前页的文件列表
        List<conversion.bean.Plugin> currentPageFiles = allPlugins.subList(startIndex, Math.min(startIndex + pageSize, allPlugins.size()));

        // 将当前页的文件列表添加到 resultMap
        resultMap.put("pluginList", currentPageFiles);

        // 计算总页数
        int totalPage = (int) Math.ceil((double) allPlugins.size() / pageSize);

        // 将总页数添加到 resultMap
        resultMap.put("totalPage", totalPage);

        //返回结果给前端
        return resultMap;
    }


    @GetMapping("/deletePlugin")
    public void deletePlugin(@RequestParam("id")int id){
        pluginService.deletePlugin(id);

    }

    @GetMapping("/disablePlugin")
    public void disablePlugin(@RequestParam("id")int id){
        pluginService.updatePluginLoadStatus(id,false);

    }

    @GetMapping("/startupPlugin")
    public void startupPlugin(@RequestParam("id")int id){
        pluginService.updatePluginLoadStatus(id,true);

    }


}
